<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container-TmptAuthDept">
        <el-input
          placeholder="输入关键字进行过滤"
          class="filter-item"
          v-model="filterText"
          size="mini"
          style="width: 200px; "
        />
        <!--<el-button class="filter-item" size="mini" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          添加
        </el-button>-->
    </div>

    <el-scrollbar :style="{height:treeHeight}">
      <el-tree
        ref="tree"
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }} {{(isNull(data.level) || data.level==0)?'':"(Level:"+data.level+")"}}</span>
          <span>
            <!--<el-button
              type="text"
              size="mini"
              @click="() => handleCreate(data)">
              添加
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => handleUpdate(data)">
              编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => handleDelete(node, data)">
              删除
            </el-button>-->
          </span>
        </span>
      </el-tree>
    </el-scrollbar>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <form-details ref="formDetails" :row="row" :isModule="true" @createResult="createResult" @updateResult="updateResult"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeApi, deleteApi } from './api'
import FormDetails from './form-details.vue' // add form form dialog


export default {
    name: 'TmptAuthDept-MyTree',
    components: { FormDetails },
    props: {
        isModule: {
            type: Boolean,
            default: false
        }
    },

    data() {
        return {
            treeData: [],
            defaultProps: {
                children: 'tmptAuthDeptList',
                label: 'name' // 请换成对应展示属性 **************
            },
            filterText: undefined,
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: '编辑',
                create: '添加'
            },
            row: {},
            treeHeight: '500px',
            clientHeight: 0, // 浏览器高度
        }
    },

    watch: {
        filterText(val) {
            this.$refs.tree.filter(val)
        }
    },

    mounted() {
        this.initTree();

        const reduceNumber = 230;
        this.clientHeight = `${document.documentElement.clientHeight}`;//获取浏览器可视区域高度
        this.treeHeight = (this.clientHeight - reduceNumber)+'px'
        // vue中使用两个window.onresize问题解决
        // https://blog.csdn.net/asm35548/article/details/101797302
        /*window.onresize = () => {
          return (() => {
            this.clientHeight = `${document.documentElement.clientHeight}`;
            this.treeHeight = (this.clientHeight - reduceNumber)+'px'
            console.log(this.treeHeight)
          })()
        }*/
        window.addEventListener('resize',() => {return (() => {
          this.clientHeight = `${document.documentElement.clientHeight}`;
          this.treeHeight = (this.clientHeight - reduceNumber)+'px'
        })()}, false)
    },

    methods: {
        initTree() {
            // 默认root node id = 1  *********
            const rootNodeId = 0
            treeApi({ id: rootNodeId }).then((result) => {
              if (result.success) {
                  this.treeData = result.obj.tmptAuthDeptList
              }
            })
        },
        handleNodeClick(row) {
            // 从父组件调用此方法，进行回调下
            if (this.isModule) {
                row.parentPropName = 'tmptAuthDeptId'
                this.$emit('input', row)
            }
        },
        filterNode(value, data) {
            if (!value) return true
            const propValue = ''+data.name  // 请换成对应展示属性 ************
            return propValue.indexOf(value) !== -1
        },
        // 接收页面请求
        handleCreate(row) {
            if (row===undefined || row.id===undefined) row.id = 0 // root node
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
                this.$refs['formDetails'].resetTemp()
                this.$refs['formDetails'].defaultTemp()
                this.$refs['formDetails'].setParentNodeId(row.id)
            })
        },
        // 调用子组件操作数据
        createData() {
            this.$refs['formDetails'].createData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        createResult() {
            this.dialogFormVisible = false
            this.initTree()
            /* const newChild = { id: id++, label: 'testtest', children: [] }
            if (!data.children) {
                this.$set(data, 'children', [])
            }
            data.children.push(newChild)*/
        },
        // 接收页面Update请求
        handleUpdate(row) {
            this.row = Object.assign({}, row) // copy obj
            this.row.deleteflag = this.row.deleteflag.id // 枚举对象，取id值
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
            })
        },
        // 调用子组件操作数据
        updateData() {
            this.$refs['formDetails'].updateData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        updateResult() {
            this.dialogFormVisible = false
            this.initTree()
        },
        // 删除
        handleDelete(node, data) {
            this.$confirm('确认删除吗？').then(_ => {
                // delete api
                deleteApi({ id: ''+data.id }).then((r) => {
                    this.notify(r)
                    if (r.success) {
                        this.initTree()
                    }
                })
                // end
            }).catch(_ => {})
        }
    } // method end
}
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
